<template>
  <WidgetBase
    ref="root"
    class="fa-widget-sign"
    :data="data"
    :menu="menu"
    :draggable="!ridingClosed"
    :clearable="!!data.signImage"
    @click="onClick"
    :style="data.isRiding && !ridingClosed ? `margin-left: ${-data.w / 2}px` : ''"
  >
    <div v-if="data.signImage" class="fa-widget-sign__img-box">
      <SignImg class="fa-widget-sign__img" :style="signImgStyle" :type="type" :data="data.sign" />
    </div>

    <WidgetPlaceholder v-else-if="!data.isDone" :data="data" vertical :text="widgetText" />
  </WidgetBase>
</template>

<script lang="ts">
import { computed, defineComponent, inject, ref } from 'vue'
import { Message } from 'element-ui'
import { Widget } from '@/models'
import { Viewer, WidgetMenuItem, SignType, ContractPage } from '@/types'
import { PopoverType } from '@/components/contract/useWidgetPopover'
import { getApplyCount } from '@/models/widget/batch'
import WidgetBase from '@/components/widget-base/WidgetBase.vue'
import SignImg from '@/components/sign-img/SignImg.vue'
import WidgetPlaceholder from '@/components/widget-base/WidgetPlaceholder.vue'

/** 签署控件 */
export default defineComponent({
  name: 'FaWidgetSign',

  components: { WidgetBase, SignImg, WidgetPlaceholder },

  props: {
    /** 控件数据 */
    data: {
      type: Widget,
      required: true
    },

    /** 骑缝区域关闭 */
    ridingClosed: {
      type: Boolean,
      default: false
    }
  },

  setup(props, { emit }) {
    /** 合同控件 */
    const viewer = inject('Viewer') as Viewer

    /** 所在页面 */
    const Page = inject('ContractPage') as ContractPage

    /** 根组件 */
    const root = ref(null as InstanceType<typeof WidgetBase> | null)

    /** 根节点 */
    const el = computed(() => root.value?.$el as HTMLElement | null)

    /** 控件名称展示 */
    const widgetText = computed(() => {
      // 指定印章
      if (props.data.assignedSignId) {
        return viewer?.seals?.find(i => i.id === props.data.assignedSignId)?.name ?? props.data.assignedSignName
      }

      // 骑缝控件
      if (props.data.isRiding) return '骑缝章'

      // 默认控件名称
      return ''
    })

    /** 触发切换签章 */
    function changeSign() {
      // 无指定印章权限
      if (props.data.assignedSignId && !viewer?.seals?.find(i => i.id === props.data.assignedSignId)) {
        Message.warning(`发起方指定此处使用“${widgetText.value}”进行签署，您暂无该印章无法加盖`)
        return
      }

      viewer.$emit('popover-open', PopoverType.SIGN_CHANGE, el.value, props.data)
    }

    /** 触发签章规格 */
    function changeSignSpec() {
      viewer.$emit('popover-open', PopoverType.SIGN_SPEC, el.value, props.data)
    }

    return {
      /** 根组件 */
      root,

      /** 签章类型 */
      type: computed(() => props.data.option.key as unknown as SignType),

      /**
       * 签章图片样式
       * @description 骑缝控件在已完成模式或骑缝区域关闭时按页码数平均宽度展示，
       * 因此图片需要固定尺寸避免缩小
       */
      signImgStyle: computed(() => {
        const widget = props.data

        let width = '100%'
        let left = '0%'

        if (widget.isRidingStyle) {
          const { w, displayWidth, applyPage } = widget

          const total = widget.doc?.pages.length || 0

          width = `${widget.w - 2}px`

          const p = getApplyCount(Page.page.p + 1, applyPage) - 1

          const totalIndex = getApplyCount(total, applyPage) - 1

          if (totalIndex) left = `-${(p / totalIndex) * (w - displayWidth)}px`
        }

        return { width, transform: `translateX(${left})` }
      }),

      /** 操作菜单 */
      menu: computed(() => {
        const widget = props.data
        const hasImg = !!widget.signImage

        if (widget.isRiding && props.ridingClosed) return []

        return [
          {
            text: '批量应用',
            enable: widget.batchable,
            handler: () => viewer.$emit('popover-open', PopoverType.BATCH_APPLY, el.value, widget)
          },
          {
            text: `${hasImg ? '更换' : '设置'}${widget.option.name}`,
            enable: widget.signChangeable,
            handler: changeSign
          },
          {
            text: `${widget.option.name}规格`,
            enable: widget.signResizable,
            handler: changeSignSpec
          }
        ] as WidgetMenuItem[]
      }),

      /** 控件名称展示 */
      widgetText,

      /** 签章点击 */
      onClick() {
        const { ridingClosed } = props

        // 骑缝区域关闭时点击展开骑缝区域
        if (ridingClosed) emit('riding-open')

        const { signChangeable, signImage } = props.data

        // 未设置签章时点击控件触发选择签章
        if (!ridingClosed && signChangeable && !signImage) changeSign()
      }
    }
  }
})
</script>

<style lang="scss">
// 签署控件签名、印章
.fa-widget-sign {
  &__img {
    height: 100%;
    transition: all 0.3s linear;

    &-box {
      width: 100%;
      height: 100%;
      overflow: hidden;
    }

    .fa-sign-img__target {
      opacity: 0.9;
    }
  }

  &.fa-widget-seal .fa-sign-img__target {
    background-size: contain;
  }
}

// 骑缝区域
.fa-riding-area {
  $mw: calc(100% + 2px);

  .fa-widget-sign {
    margin: -1px 0 0 -1px;
  }

  // 骑缝展开
  &:not(.is-close) .fa-widget-sign {
    left: 50%;
    margin-left: 0;

    .fa-sign-img {
      max-width: 100%;
    }
  }

  // 骑缝收起
  &.is-close .fa-widget-sign {
    right: 0;
    left: auto;
    cursor: pointer;

    .fa-widget-toolbar__wrap,
    .fa-widget__close {
      display: none;
    }

    .fa-widget-placeholder {
      padding: 0 4px;
    }
  }
}
</style>
